package com.devinlee.mode.containers;

import com.devinlee.mode.annotation.RoleTypeHandler;
import com.devinlee.mode.service.IRoleService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 角色接口实现容器
 * <p>
 * Created by devinlee in 2021.10.26
 */
@Component
public class RoleContainer implements ApplicationContextAware {

    //code与具体实现类的对应关系
    private static final Map<Integer, IRoleService> roleServiceMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取所有标记了@RoleType注解的实现类
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(RoleTypeHandler.class);
        beansWithAnnotation.forEach((k, v) -> {
            roleServiceMap.put(v.getClass().getAnnotation(RoleTypeHandler.class).value().code(), (IRoleService) v);
        });
    }

    /**
     * 获取对应实现类
     * @param code
     * @return
     */
    public IRoleService get(int code){
        return roleServiceMap.get(code);
    }
}
